package com.shujia.scala

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}

import scala.io.{BufferedSource, Source}

object Demo5Base {
  def main(args: Array[String]): Unit = {
    /**
      * 变量和常量
      * val : 常量
      * var : 变量
      *
      */

    val a: Int = 1
    var str: String = "java"


    /**
      * 循环
      *
      */


    val array: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)


    //增强for循环
    for (i <- array) {
      println(i)
    }

    println("=" * 100)

    //while 循环

    var i = 0

    while (i < array.length) {

      //通过下标获取元素
      println(array(i))

      i += 1
    }

    println("=" * 100)

    /**
      * foreach
      *
      * (i => println(i))  匿名函数
      */

    array.foreach(i => println(i))


    /**
      * io流: scala可以使用java中的io流
      *
      */

    println("=" * 100)

    //链式调用
    val lines: Iterator[String] = Source.fromFile("data/students.txt").getLines()

    for (line <- lines) {
      println(line)
    }


    println("=" * 100)
    /**
      * scala 植复仇拼接
      *
      */

    //java的方式
    val s: String = "java" + "scala" + "hadoop"


    val stringBuffer = new StringBuffer()

    stringBuffer
      .append("java")
      .append("scala")
      .append("hadoop")

    println(stringBuffer.toString)


    /**
      * scala 字符串拼接
      *
      */


    val s2 = "java"
    val s3 = "scala"
    val s4 = "hadaoop"

    val s5 = s"$s2$s3${s4}shujia"

    println(s5)


    /**
      * jdbc
      */


    //1\加载驱动
    Class.forName("com.mysql.jdbc.Driver")

    //2、创建链接
    val con: Connection = DriverManager.getConnection("jdbc:mysql://rm-bp1h7v927zia3t8iwho.mysql.rds.aliyuncs.com:3306/students", "shujia012", "123456")

    //3、查询数据
    val stat: PreparedStatement = con.prepareStatement("select * from students")

    //4、执行查询
    val resultSet: ResultSet = stat.executeQuery()

    while (resultSet.next()) {
      val id: Long = resultSet.getLong("id")
      val age: Long = resultSet.getLong("age")
      val name: String = resultSet.getString("name")
      val clazz: String = resultSet.getString("clazz")
      val gender: String = resultSet.getString("gender")

      println(s"$id\t$name\t$age\t$gender\t$clazz")

    }

    //关闭链接
    con.close()

  }

}
